package redis

import (
	"context"
	"fmt"
	"rpc/pb/cart"
	"strconv"
)

func AddCart(goods map[string]interface{}) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", goods["user_id"], goods["goods_id"])
	return Rdb.HMSet(context.Background(), key, goods).Err()
}

func GetExists(userId int64, goodsId int64) bool {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}
func UpdateCart(userId int64, goodsId int64, num int64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HIncrBy(context.Background(), key, "num", num).Err()
}
func ListCart(userId int64) (goodslist []*cart.GoodsItem, err error) {
	key := fmt.Sprintf("cart:user_id_%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()

	for _, v := range keys {
		goodsMap := Rdb.HGetAll(context.Background(), v).Val()
		userid, _ := strconv.Atoi(goodsMap["user_id"])
		goodsid, _ := strconv.Atoi(goodsMap["goods_id"])
		goodsPrice, _ := strconv.ParseFloat(goodsMap["price"], 64)
		goodsStock, _ := strconv.Atoi(goodsMap["goods_stock"])
		goodsStatus, _ := strconv.Atoi(goodsMap["goods_status"])

		list := &cart.GoodsItem{
			GoodsTitle:  goodsMap["goods_title"],
			GoodsPrice:  float32(goodsPrice),
			GoodsImg:    goodsMap["goods_img"],
			GoodsStatus: int64(goodsStock),
			GoodsStock:  int64(goodsStatus),
			UserId:      int64(userid),
			GoodsId:     int64(goodsid),
		}
		goodslist = append(goodslist, list)
	}
	return
}
